package com.ruoyi.enterwarehouse.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.order.OrderUtils;
import com.ruoyi.enterwarehouse.domain.TGoodsBigitImport;
import com.ruoyi.enterwarehouse.domain.WEnterWarehouseImport;
import com.ruoyi.enterwarehouse.domain.TGoodsEnterImport;
import com.ruoyi.goods.domain.TGoodsInfo;
import com.ruoyi.goods.domain.TGoodsWeightSum;
import com.ruoyi.goods.domain.WGoodsExt;
import com.ruoyi.goods.domain.WGoodsExtAssist;
import com.ruoyi.goods.service.ITGoodsInfoService;
import com.ruoyi.goods.service.IWGoodsExtAssistService;
import com.ruoyi.goods.service.IWGoodsExtService;
import com.ruoyi.system.domain.TVehicleDriverInfo;
import com.ruoyi.system.service.ITVehicleDriverInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.enterwarehouse.domain.WEnterWarehouseInfo;
import com.ruoyi.enterwarehouse.service.IWEnterWarehouseInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入库信息Controller
 * 
 * @author wzy
 * @date 2024-05-26 11:12:40
 */
@RestController
@RequestMapping("/enterwarehouse/enter")
public class WEnterWarehouseInfoController extends BaseController
{
    @Autowired
    private IWEnterWarehouseInfoService wEnterWarehouseInfoService;

    @Autowired
    private ITGoodsInfoService tGoodsInfoService;

    @Autowired
    private ITVehicleDriverInfoService tVehicleDriverInfoService;

    @Autowired
    private IWGoodsExtService wGoodsExtService;

    @Autowired
    private IWGoodsExtAssistService wGoodsExtAssistService;

    private static Logger logger = LoggerFactory.getLogger(WEnterWarehouseInfoController.class);
    /**
     * 查询入库信息列表
     */
    @PreAuthorize("@ss.hasAnyPermi('enterwarehouse:enter:list, enterwarehouse:plan:list, enterwarehouse:task:list, enterwarehouse:receipt:list')")
    @GetMapping("/list")
    public TableDataInfo list(WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        startPage();
        List<WEnterWarehouseInfo> list = wEnterWarehouseInfoService.selectWEnterWarehouseInfoList(wEnterWarehouseInfo);
        return getDataTable(list);
    }

    /**
     * 导出入库信息列表
     */
    @PreAuthorize("@ss.hasAnyPermi('enterwarehouse:enter:export, enterwarehouse:plan:export, enterwarehouse:task:export, enterwarehouse:receipt:export')")
    @Log(title = "入库信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        List<WEnterWarehouseInfo> list = wEnterWarehouseInfoService.selectWEnterWarehouseInfoList(wEnterWarehouseInfo);
        ExcelUtil<WEnterWarehouseInfo> util = new ExcelUtil<WEnterWarehouseInfo>(WEnterWarehouseInfo.class);
        util.exportExcel(response, list, "入库信息数据");
    }

    /**
     * 获取入库信息详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('enterwarehouse:enter:query, enterwarehouse:plan:query, enterwarehouse:task:query, enterwarehouse:receipt:query')")
    @GetMapping(value = "/{enterWarehouseId}")
    public AjaxResult getInfo(@PathVariable("enterWarehouseId") Long enterWarehouseId)
    {
        return success(wEnterWarehouseInfoService.selectWEnterWarehouseInfoByEnterWarehouseId(enterWarehouseId));
    }

    /**
     * 新增入库信息
     */
    @PreAuthorize("@ss.hasAnyPermi('enterwarehouse:enter:add, enterwarehouse:plan:add, enterwarehouse:task:add, enterwarehouse:receipt:add')")
    @Log(title = "入库信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        wEnterWarehouseInfo.setEnterWarehouseNumber(OrderUtils.getOrderNumber("EN", "-"));
        wEnterWarehouseInfo.setCreateBy(getNickName());
        updateMobileAndNumberRelateInfo(wEnterWarehouseInfo);
        wEnterWarehouseInfo.setNumberOfPiece(handleMineTGoodsInfo(BusinessType.INSERT, wEnterWarehouseInfo));
        return toAjax(wEnterWarehouseInfoService.insertWEnterWarehouseInfo(wEnterWarehouseInfo));
    }

    /**
     * 修改入库信息
     */
    @PreAuthorize("@ss.hasAnyPermi('enterwarehouse:enter:edit, enterwarehouse:plan:edit, enterwarehouse:task:edit, enterwarehouse:receipt:edit')")
    @Log(title = "入库信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        wEnterWarehouseInfo.setUpdateBy(getNickName());
        wEnterWarehouseInfo.setNumberOfPiece(handleMineTGoodsInfo(BusinessType.UPDATE, wEnterWarehouseInfo));
        return toAjax(wEnterWarehouseInfoService.updateWEnterWarehouseInfo(wEnterWarehouseInfo));
    }

    /**
     * 删除入库信息
     */
    @PreAuthorize("@ss.hasAnyPermi('enterwarehouse:enter:remove, enterwarehouse:plan:remove, enterwarehouse:task:remove, enterwarehouse:receipt:remove')")
    @Log(title = "入库信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{enterWarehouseIds}")
    public AjaxResult remove(@PathVariable Long[] enterWarehouseIds)
    {
        tGoodsInfoService.deleteTGoodsInfoByOtherIdsExt(0 /*入库Ids*/, enterWarehouseIds);
        return toAjax(wEnterWarehouseInfoService.deleteWEnterWarehouseInfoByEnterWarehouseIds(enterWarehouseIds));
    }

    /**
     * 修改入库单状态，确认入库
     */
    //@PreAuthorize("@ss.hasPermi('enterwarehouse:enter:edit')")
    @Log(title = "确认入库", businessType = BusinessType.CONFIRM)
    @PutMapping("/confirm")
    public AjaxResult confirm(@RequestBody WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        wEnterWarehouseInfo.setUpdateBy(getNickName());
        wEnterWarehouseInfo.setEnterWarehouseConfirmPerson(getNickName());
        wEnterWarehouseInfo.setEnterWarehouseConfirmTime(DateUtils.getNowDate());
        tGoodsInfoService.updateTGoodsConfirmRelFieldsByEnterWarehouseNumber(wEnterWarehouseInfo, "已在库");
        handleMineInventory(BusinessType.CONFIRM, wEnterWarehouseInfo);
        wEnterWarehouseInfo.setJobStatus("3");
        Integer rtn = wEnterWarehouseInfoService.updateWEnterWarehouseInfo(wEnterWarehouseInfo);
        return toAjax(rtn);
    }

    /**
     * 修改入库单状态，撤销入库
     */
    //@PreAuthorize("@ss.hasPermi('enterwarehouse:enter:edit')")
    @Log(title = "撤销入库", businessType = BusinessType.REVOKE)
    @PutMapping("/revoke")
    public AjaxResult revoke(@RequestBody WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        /* 检查是否可以撤销，出库中，已出库，货转中，货转过，不允许撤销。 */
        if (StringUtils.isNull(wEnterWarehouseInfo))
        {
            throw new ServiceException("入库记录不能为空！");
        }
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        List<TGoodsInfo> goodsList = tGoodsInfoService.selectTGoodsInfoByNumber(2, wEnterWarehouseInfo.getEnterWarehouseNumber());
        for (TGoodsInfo goods : goodsList)
        {
            try
            {
                // 检查货物状态，出库中，已出库，货转中，
                if (goods.getInventoryStatus().equals("已在库"))
                {
                    // 检查货物状态，是否货转过
                    if(goods.getGoodsTransferTimes() > 0)
                    {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、货物 " + goods.getBundleNumber() + " 货转过");
                    }
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、货物 " + goods.getBundleNumber() + " " + goods.getInventoryStatus());
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、入库单据 " + wEnterWarehouseInfo.getEnterWarehouseNumber() + " 撤销失败：";
                failureMsg.append(msg + e.getMessage());
                logger.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，撤销失败！共 " + failureNum + " 条数货物状态不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
//        return successMsg.toString();
//        logger.debug("WWW " + "wEnterWarehouseInfo = " + wEnterWarehouseInfo);
        wEnterWarehouseInfo.setUpdateBy(getNickName());
        wEnterWarehouseInfo.setEnterWarehouseConfirmPerson(null);
        wEnterWarehouseInfo.setEnterWarehouseConfirmTime(null);
        tGoodsInfoService.updateTGoodsConfirmRelFieldsByEnterWarehouseNumber(wEnterWarehouseInfo, "入库中");
        handleMineInventory(BusinessType.REVOKE, wEnterWarehouseInfo);
        wEnterWarehouseInfo.setJobStatus("2");
        Integer rtn = wEnterWarehouseInfoService.updateWEnterWarehouseInfo(wEnterWarehouseInfo);
        return toAjax(rtn);
    }
    private void updateMobileAndNumberRelateInfo(WEnterWarehouseInfo wEnterWarehouseInfo) {
        TVehicleDriverInfo tVehicleDriverInfo = new TVehicleDriverInfo();

        //更新车牌，司机，电话
        if(!(wEnterWarehouseInfo.getEnterWarehouseVehicle() == null || wEnterWarehouseInfo.getEnterWarehouseVehicle().isEmpty())) {
//            logger.debug("HHH " + "edit = " + tVehicleDriverInfo);
            tVehicleDriverInfo.setVehicleLicenseNumber(wEnterWarehouseInfo.getEnterWarehouseVehicle());
            List<TVehicleDriverInfo> list = tVehicleDriverInfoService.selectTVehicleDriverInfoByNumber(tVehicleDriverInfo);
            tVehicleDriverInfo.setDriverName(wEnterWarehouseInfo.getEnterWarehouseDriver());
            tVehicleDriverInfo.setContactMobile(wEnterWarehouseInfo.getEnterWarehouseMobile());
            if (list.isEmpty()) {
                tVehicleDriverInfo.setCreateBy(getNickName());
                tVehicleDriverInfo.setUpdateBy(null);
                tVehicleDriverInfo.setUpdateBy(null);
                tVehicleDriverInfoService.insertTVehicleDriverInfo(tVehicleDriverInfo);
            } else {
                tVehicleDriverInfo.setVehicleDriverId(list.get(0).getVehicleDriverId());
                tVehicleDriverInfo.setUpdateBy(getNickName());
                tVehicleDriverInfoService.updateTVehicleDriverInfo(tVehicleDriverInfo);
            }
        } else {
            logger.debug("Vehicle HHH Number is empty ");
        }
//
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TGoodsEnterImport> util = new ExcelUtil<TGoodsEnterImport>(TGoodsEnterImport.class);
        util.importTemplateExcel(response, "货物数据");
    }

    @PostMapping("/importBigitTemplate")
    public void importBigitTemplate(HttpServletResponse response)
    {
        ExcelUtil<TGoodsBigitImport> util = new ExcelUtil<TGoodsBigitImport>(TGoodsBigitImport.class);
        util.importTemplateExcel(response, "货物数据");
    }

    @Log(title = "入库作业", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String enterWarehouseNumber) throws Exception
    {
        //避免导入货物，入库单号，为null
        if(enterWarehouseNumber == null || enterWarehouseNumber.isEmpty() || enterWarehouseNumber.equals("null")) {
            return error("入库单号为空，导入失败！");
        }
        //logger.debug("CCC " + "getAvatarPath = " + RuoYiConfig.getImportPath());
        //logger.debug("CCC " + "file = " + file);
        //logger.debug("CCC " + "enterWarehouseNumber = " + enterWarehouseNumber);
        //logger.debug("AAA " + "MimeTypeUtils.IMAGE_EXTENSION = " + MimeTypeUtils.IMAGE_EXTENSION);
        String xmlfile = FileUploadUtils.upload(RuoYiConfig.getImportPath(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        ExcelUtil<TGoodsEnterImport> util = new ExcelUtil<TGoodsEnterImport>(TGoodsEnterImport.class);
        List<TGoodsEnterImport> goodsList = util.importExcel(file.getInputStream());
        //logger.debug("CCC " + "goodsList = " + goodsList);
        String operName = getNickName();
        String message = tGoodsInfoService.importGoods(goodsList, enterWarehouseNumber, operName);
        int rtn = wEnterWarehouseInfoService.updateWEnterTotalWeightPieceByNumber(enterWarehouseNumber);
        if(rtn == 0)
        {
            logger.error("XXX importData " + "update Enter Total Weight Piece error");
        }

        return success(message);
    }

    @Log(title = "入库作业", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importBigitData")
    public AjaxResult importBigitData(MultipartFile file, String enterWarehouseNumber) throws Exception
    {
        //避免导入货物，入库单号，为null
        if(enterWarehouseNumber == null || enterWarehouseNumber.isEmpty() || enterWarehouseNumber.equals("null")) {
            return error("入库单号为空，导入失败！");
        }
        String xmlfile = FileUploadUtils.upload(RuoYiConfig.getImportPath(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        ExcelUtil<TGoodsBigitImport> util = new ExcelUtil<TGoodsBigitImport>(TGoodsBigitImport.class);
        List<TGoodsBigitImport> goodsList = util.importExcel(file.getInputStream());
        //logger.debug("CCC " + "goodsList = " + goodsList);
        String operName = getNickName();
        String message = tGoodsInfoService.importGoodsBigit(goodsList, enterWarehouseNumber, operName);
        int rtn = wEnterWarehouseInfoService.updateWEnterTotalWeightPieceByNumber(enterWarehouseNumber);
        if(rtn == 0)
        {
            logger.error("XXX importData " + "update Enter Total Weight Piece error");
        }

        return success(message);
    }

    @PostMapping("/enterTaskTemplate")
    public void enterTemplate(HttpServletResponse response)
    {
        ExcelUtil<WEnterWarehouseImport> util = new ExcelUtil<WEnterWarehouseImport>(WEnterWarehouseImport.class);
        util.importTemplateExcel(response, "入库导入数据");
    }

    @Log(title = "入库作业", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importEnterTask")
    public AjaxResult importEnter(MultipartFile file) throws Exception
    {
//        logger.debug("CCC " + "getAvatarPath = " + RuoYiConfig.getImportPath());
//        logger.debug("CCC " + "file = " + file);
        //logger.debug("AAA " + "MimeTypeUtils.IMAGE_EXTENSION = " + MimeTypeUtils.IMAGE_EXTENSION);
        String xmlfile = FileUploadUtils.upload(RuoYiConfig.getImportPath(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);

        ExcelUtil<WEnterWarehouseImport> util = new ExcelUtil<WEnterWarehouseImport>(WEnterWarehouseImport.class);
        List<WEnterWarehouseImport> enterList = util.importExcel(file.getInputStream());
//        logger.debug("CCC " + "enterList = " + enterList);

        String operName = getNickName();
        String message = wEnterWarehouseInfoService.importEnterTask(enterList, operName);
        return success(message);
    }

    /**
     * 获取货物重量合计
     */
    @GetMapping(value = "/enterweightsum")
    public AjaxResult enterWeightSum(WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        List<TGoodsWeightSum> list = wEnterWarehouseInfoService.getWeightSumByEnterWarehouseInfo(wEnterWarehouseInfo);
//        logger.debug("GGG " + "getWeightSumByEnterWarehouseInfo = " + list);
        return success(list);
    }

    /**
     * 处理矿物（煤炭，矿粉），货物信息
     * @param operate，
     * @param wEnterWarehouseInfo
     */
    private Integer handleMineTGoodsInfo(BusinessType operate, WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        Integer numberOfPiece = 0;
        if (!wEnterWarehouseInfo.getGoodsType().equals("煤炭"))
        {
            return 0;
        }
        /**
         * 插入货物
         */
        if(BusinessType.INSERT == operate)
        {
            numberOfPiece = insertMineTGoodsInfo(wEnterWarehouseInfo);
        }

        /**
         * 修改货物，先删除货物，后插入货物
         */
        if(BusinessType.UPDATE == operate)
        {
            /**
             * 删除货物，物理删除
             */
            tGoodsInfoService.deleteTGoodsInfoByNumberExt(0 /*入库单号*/,wEnterWarehouseInfo.getEnterWarehouseNumber());
            /**
             * 插入货物
             */
            numberOfPiece = insertMineTGoodsInfo(wEnterWarehouseInfo);
        }

        return numberOfPiece;
    }

    /**
     * 插入货物信息
     * @param wEnterWarehouseInfo
     */
    private Integer insertMineTGoodsInfo(WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        Integer numberOfPiece = 0;
        /**
          * 拆分入库货物，毛重大于50吨
          */
        TGoodsInfo tGoodsInfo = new TGoodsInfo();
//            String vehicle = wEnterWarehouseInfo.getEnterWarehouseVehicle().substring(1);
//            logger.debug("QQQ " + "vehicle = " + vehicle);

        tGoodsInfo.setBundleNumber(OrderUtils.getOrderNumber("CL", "-"));
        tGoodsInfo.setGoodsType(wEnterWarehouseInfo.getGoodsType());
        tGoodsInfo.setProduct(wEnterWarehouseInfo.getProduct());
        tGoodsInfo.setSpecification(wEnterWarehouseInfo.getSpecification());
        tGoodsInfo.setSteelGrade(wEnterWarehouseInfo.getSteelGrade());
        tGoodsInfo.setWeight(wEnterWarehouseInfo.getWeight());
        tGoodsInfo.setGrossWeight(wEnterWarehouseInfo.getGrossWeight());
        tGoodsInfo.setTareWeight(wEnterWarehouseInfo.getTareWeight());
        tGoodsInfo.setNetWeight(wEnterWarehouseInfo.getNetWeight());
        tGoodsInfo.setDeductWeight(wEnterWarehouseInfo.getDeductWeight());
        tGoodsInfo.setRecordSource(wEnterWarehouseInfo.getRecordSource());
        tGoodsInfo.setInventoryStatus("入库中");
        tGoodsInfo.setWarehouseType(wEnterWarehouseInfo.getWarehouseType());
        tGoodsInfo.setLogisticsParkName(wEnterWarehouseInfo.getLogisticsParkName());
        tGoodsInfo.setWarehouseLocateName(wEnterWarehouseInfo.getWarehouseLocateName());
        tGoodsInfo.setRegionLocateName(wEnterWarehouseInfo.getRegionLocateName());
        tGoodsInfo.setGoodsLocateName(wEnterWarehouseInfo.getGoodsLocateName());
        tGoodsInfo.setWarehouseTotalLocate(wEnterWarehouseInfo.getWarehouseTotalLocate());

        tGoodsInfo.setEnterWarehouseNumber(wEnterWarehouseInfo.getEnterWarehouseNumber());
        tGoodsInfo.setEnterWarehouseCustomer(wEnterWarehouseInfo.getEnterWarehouseCustomer());
        tGoodsInfo.setEnterWarehouseDriver(wEnterWarehouseInfo.getEnterWarehouseDriver());
        tGoodsInfo.setEnterWarehouseVehicle(wEnterWarehouseInfo.getEnterWarehouseVehicle());
        tGoodsInfo.setEnterWarehousePerson(wEnterWarehouseInfo.getCreateBy());
        tGoodsInfo.setEnterWarehouseTime(wEnterWarehouseInfo.getEnterWarehouseTime());
        tGoodsInfo.setGoodsRightCustomer(wEnterWarehouseInfo.getEnterWarehouseCustomer());

        tGoodsInfo.setCreateBy(getNickName());
        logger.debug("QQQ " + "wEnterWarehouseInfo = " + wEnterWarehouseInfo);
        if (StringUtils.isNotNull(wEnterWarehouseInfo.getGrossWeight()) && (wEnterWarehouseInfo.getGrossWeight() > 55.0)) {
            double weight = wEnterWarehouseInfo.getWeight();
            double grossWeight = wEnterWarehouseInfo.getGrossWeight();
            double tareWeight = wEnterWarehouseInfo.getTareWeight();
            double netWeight = wEnterWarehouseInfo.getNetWeight();
            double deductWeight = wEnterWarehouseInfo.getDeductWeight();
            weight = Math.round(weight / 2.0 * 1000.0) / 1000.0;
            grossWeight = Math.round((grossWeight + tareWeight) / 2.0 * 1000.0) / 1000.0;
            netWeight = Math.round(netWeight / 2.0 * 1000.0) / 1000.0;
            deductWeight = Math.round(deductWeight / 2.0 * 1000.0) / 1000.0;

            tGoodsInfo.setWeight(weight);
            tGoodsInfo.setGrossWeight(grossWeight);
//            tGoodsInfo.setTareWeight(tareWeight);
            tGoodsInfo.setNetWeight(netWeight);
            tGoodsInfo.setDeductWeight(deductWeight);
            tGoodsInfoService.insertTGoodsInfo(tGoodsInfo);

            tGoodsInfo.setGrossWeight(Math.round((wEnterWarehouseInfo.getGrossWeight() - grossWeight + tareWeight) * 1000.0) / 1000.0);
//            tGoodsInfo.setTareWeight(tareWeight);
            tGoodsInfo.setNetWeight(Math.round((wEnterWarehouseInfo.getNetWeight() - netWeight) * 1000.0) / 1000.0);
            tGoodsInfo.setDeductWeight(Math.round((wEnterWarehouseInfo.getDeductWeight() - deductWeight) * 1000.0) / 1000.0);
//            tGoodsInfo.setBundleNumber(OrderUtils.getOrderNumber(vehicle, "-"));
            tGoodsInfo.setBundleNumber(OrderUtils.getOrderNumber("CL", "-"));
            tGoodsInfoService.insertTGoodsInfo(tGoodsInfo);

            numberOfPiece = 2;
        } else {
            tGoodsInfoService.insertTGoodsInfo(tGoodsInfo);
        }
        return numberOfPiece;
    }

    /**
     * 处理煤炭库存
     * @param operate
     * @param wEnterWarehouseInfo
     */
    private void handleMineInventory(BusinessType operate, WEnterWarehouseInfo wEnterWarehouseInfo)
    {
        WGoodsExt wGoodsExt = new WGoodsExt();
        WGoodsExtAssist wGoodsExtAssist = new WGoodsExtAssist();
        wGoodsExt.setGoodsType(wEnterWarehouseInfo.getGoodsType());
        wGoodsExt.setProduct(wEnterWarehouseInfo.getProduct());
        wGoodsExt.setSpecification(wEnterWarehouseInfo.getSpecification());
        //wGoodsExt.setSteelGrade(wEnterWarehouseInfo.getSteelGrade());

        //wGoodsExt.setWarehouseType(wEnterWarehouseInfo.getWarehouseType());
        wGoodsExt.setLogisticsParkName(wEnterWarehouseInfo.getLogisticsParkName());
        wGoodsExt.setWarehouseLocateName(wEnterWarehouseInfo.getWarehouseLocateName());
        wGoodsExt.setRegionLocateName(wEnterWarehouseInfo.getRegionLocateName());
        //wGoodsExt.setGoodsLocateName(wEnterWarehouseInfo.getGoodsLocateName());
        //wGoodsExt.setLayerLocateName(wEnterWarehouseInfo.setLayerLocateName());
        //wGoodsExt.setWarehouseTotalLocate(wEnterWarehouseInfo.getWarehouseTotalLocate());
        wGoodsExt.setGoodsRightCustomer(wEnterWarehouseInfo.getEnterWarehouseCustomer());

        Integer record = wGoodsExtService.selectWGoodsExtRecordCountByGoodsExt(wGoodsExt);
        /**
         * 确认入库
         */
        if(BusinessType.CONFIRM == operate) {
            //logger.debug("GGG " + "handleMineInventory = " + wEnterWarehouseInfo);
            if(record > 0) {
                WGoodsExt goodsExt = wGoodsExtService.selectWGoodsExtOneByGoodsExt(wGoodsExt);
                double weight = goodsExt.getWeight();
                weight = weight + wEnterWarehouseInfo.getWeight();
                weight = Math.round(weight * 1000.0) / 1000.0;
                goodsExt.setWeight(weight);
                goodsExt.setUpdateBy("system");
                wGoodsExtService.updateWGoodsExt(goodsExt);
                wGoodsExtAssist.setBundleNumber(goodsExt.getBundleNumber());
                wGoodsExtAssist.setBundleNumberAlias(goodsExt.getBundleNumberAlias());
            } else {
                wGoodsExt.setBundleNumber(OrderUtils.getOrderNumber("GBE", "-"));
                wGoodsExt.setBundleNumberAlias(wEnterWarehouseInfo.getEnterWarehouseCustomer().substring(0, 4) + wEnterWarehouseInfo.getWarehouseLocateName() + wEnterWarehouseInfo.getRegionLocateName());
                wGoodsExt.setCreateBy("system");
                wGoodsExtService.insertWGoodsExt(wGoodsExt);
                wGoodsExtAssist.setBundleNumber(wGoodsExt.getBundleNumber());
                wGoodsExtAssist.setBundleNumberAlias(wGoodsExt.getBundleNumberAlias());
            }
            wGoodsExtAssist.setGoodsExtAssistNumber(OrderUtils.getOrderNumber("EA", "-"));
            wGoodsExtAssist.setParentId(0L);
            wGoodsExtAssist.setLevelMark("0");
            wGoodsExtAssist.setGoodsType(wEnterWarehouseInfo.getGoodsType());
            wGoodsExtAssist.setProduct(wEnterWarehouseInfo.getProduct());
            wGoodsExtAssist.setSpecification(wEnterWarehouseInfo.getSpecification());

            wGoodsExtAssist.setWeight(wEnterWarehouseInfo.getWeight());
            wGoodsExtAssist.setGrossWeight(wEnterWarehouseInfo.getGrossWeight());
            wGoodsExtAssist.setTareWeight(wEnterWarehouseInfo.getTareWeight());
            wGoodsExtAssist.setNetWeight(wEnterWarehouseInfo.getNetWeight());
            wGoodsExtAssist.setDeductWeight(wEnterWarehouseInfo.getDeductWeight());

            wGoodsExtAssist.setInventoryStatus("已在库");
            wGoodsExtAssist.setWarehouseType(wEnterWarehouseInfo.getWarehouseType());
            wGoodsExtAssist.setLogisticsParkName(wEnterWarehouseInfo.getLogisticsParkName());
            wGoodsExtAssist.setWarehouseLocateName(wEnterWarehouseInfo.getWarehouseLocateName());
            wGoodsExtAssist.setRegionLocateName(wEnterWarehouseInfo.getRegionLocateName());
            //wGoodsExtAssist.setGoodsLocateName(wGoodsExt.getGoodsLocateName());
            //wGoodsExtAssist.setLayerLocateName(wGoodsExt.setLayerLocateName());
            wGoodsExtAssist.setWarehouseTotalLocate(wEnterWarehouseInfo.getWarehouseTotalLocate());
            wGoodsExtAssist.setGoodsRightCustomer(wEnterWarehouseInfo.getEnterWarehouseCustomer());

            wGoodsExtAssist.setRemaindWarehouseWeight(wEnterWarehouseInfo.getWeight());
            wGoodsExtAssist.setEnterWarehouseNumber(wEnterWarehouseInfo.getEnterWarehouseNumber());
            wGoodsExtAssist.setEnterWarehouseTime(wEnterWarehouseInfo.getEnterWarehouseTime());
            wGoodsExtAssist.setEnterWarehouseWeight(wEnterWarehouseInfo.getWeight());
            wGoodsExtAssist.setCreateBy("system");
            wGoodsExtAssistService.insertWGoodsExtAssist(wGoodsExtAssist);
        }

        /**
         * 撤销入库
         */
        if(BusinessType.REVOKE == operate)
        {
            if(record > 0) {
                WGoodsExt goodsExt = wGoodsExtService.selectWGoodsExtOneByGoodsExt(wGoodsExt);
                double weight = goodsExt.getWeight();
                weight = weight - wEnterWarehouseInfo.getWeight();
                weight = Math.round(weight * 1000.0) / 1000.0;
                goodsExt.setWeight(weight);
                wGoodsExtService.updateWGoodsExt(goodsExt);
            }
            wGoodsExtAssistService.deleteWGoodsExtAssistByEnterWarehouseNumber(wEnterWarehouseInfo.getEnterWarehouseNumber());
        }
    }
}
